package example.controller;

import com.alibaba.fastjson.JSON;
import example.pojo.SysRole;
import example.service.RoleService;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

@Controller
@RequestMapping(value = "/role")
public class SysRoleController {
    @Resource
    private RoleService roleService;
    private Logger logger = Logger.getLogger(SysRoleController.class);

    //角色列表
    @RequestMapping(value = "/list")
    public String list(@RequestParam(defaultValue = "1") Integer pageIndex, HttpServletRequest req, HttpServletResponse resp) {
        List<SysRole> roleList = roleService.roleList();
        if (roleList != null) {
            logger.info("角色信息获取成功");
            req.getSession().setAttribute("roleList", roleList);
            return "sysRole/list";
        } else {
            logger.debug("角色信息获取失败");
            throw new RuntimeException();
        }
    }

    //捕获异常并跳转到error
    @ExceptionHandler(value = {RuntimeException.class})
    public String handlerException(RuntimeException e, HttpServletRequest req) {
        req.setAttribute("e", e);
        return "error";
    }

    //获取角色列表
    @ResponseBody
    @GetMapping(value = "/simpleList", produces = {"application/json;charset=UTF-8"})
    public Object simpleList() {
        logger.info("获取所有的角色信息");
        List<SysRole> roleList = roleService.roleList();
        if (roleList == null || roleList.size() == 0) {
            logger.info("没有查询到角色信息");
        }
        for (SysRole sysRole : roleList) {
            System.out.println(sysRole.getId());
        }

        return JSON.toJSONString(roleList);
    }

}
